<template>
  <div class="app h-screen flex flex-col bg-white dark:bg-gray-900 overflow-hidden">
    <!-- 顶部标题栏 -->
    <div class="titlebar flex items-center justify-between px-4 py-2 bg-gray-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
      <!-- 左侧控制按钮 -->
      <div class="flex items-center space-x-2">
        <button 
          @click="toggleSidebar"
          class="p-2 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-md transition-colors"
          title="切换侧边栏"
        >
          <Menu class="w-5 h-5" />
        </button>
        <button 
          @click="newFile"
          class="p-2 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-md transition-colors"
          title="新建文件"
        >
          <Plus class="w-5 h-5" />
        </button>
        <button 
          @click="openFile"
          class="p-2 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-md transition-colors"
          title="打开文件"
        >
          <FolderOpen class="w-5 h-5" />
        </button>
        <button 
          @click="saveFile"
          class="p-2 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-md transition-colors"
          title="保存文件"
        >
          <Save class="w-5 h-5" />
        </button>
      </div>

      <!-- 中间文件名 -->
      <div class="flex items-center space-x-2">
        <span class="text-sm font-medium text-gray-700 dark:text-gray-300">{{ currentFile }}</span>
        <span v-if="isModified" class="w-2 h-2 bg-orange-500 rounded-full" title="未保存"></span>
      </div>

      <!-- 右侧功能按钮 -->
      <div class="flex items-center space-x-2">
        <button 
          @click="toggleAI"
          class="p-2 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-md transition-colors"
          :class="{ 'bg-blue-100 dark:bg-blue-900': aiOpen }"
          title="AI助手"
        >
          <Brain class="w-5 h-5" />
        </button>
        <button 
          @click="toggleGit"
          class="p-2 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-md transition-colors"
          :class="{ 'bg-green-100 dark:bg-green-900': gitOpen }"
          title="Git版本控制"
        >
          <GitBranch class="w-5 h-5" />
        </button>
        <button 
          @click="toggleSettings"
          class="p-2 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-md transition-colors"
          :class="{ 'bg-gray-100 dark:bg-gray-800': settingsOpen }"
          title="设置"
        >
          <Settings class="w-5 h-5" />
        </button>
        <button 
          @click="toggleTheme"
          class="p-2 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-md transition-colors"
          title="切换主题"
        >
          <Sun v-if="isDark" class="w-5 h-5" />
          <Moon v-else class="w-5 h-5" />
        </button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content flex flex-1 overflow-hidden">
      <!-- 左侧文件管理器 -->
      <div 
        v-if="sidebarOpen"
        class="sidebar w-64 bg-gray-50 dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700 flex flex-col"
      >
        <!-- 文件管理器标题 -->
        <div class="p-3 border-b border-gray-200 dark:border-gray-700">
          <div class="flex items-center justify-between">
            <h3 class="text-sm font-semibold text-gray-700 dark:text-gray-300 flex items-center">
              <Folder class="w-4 h-4 mr-2" />
              文件管理器
            </h3>
            <div class="flex items-center space-x-1">
              <button 
                @click="createNewFolder"
                class="p-1 hover:bg-gray-200 dark:hover:bg-gray-700 rounded"
                title="新建文件夹"
              >
                <FolderPlus class="w-4 h-4" />
              </button>
              <button 
                @click="refreshFiles"
                class="p-1 hover:bg-gray-200 dark:hover:bg-gray-700 rounded"
                title="刷新"
              >
                <RefreshCw class="w-4 h-4" />
              </button>
            </div>
          </div>
        </div>

        <!-- 文件搜索 -->
        <div class="p-3 border-b border-gray-200 dark:border-gray-700">
          <div class="relative">
            <Search class="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              v-model="searchQuery"
              type="text"
              placeholder="搜索文件..."
              class="w-full pl-10 pr-3 py-2 text-sm border border-gray-200 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
            />
          </div>
        </div>

        <!-- 文件树 -->
        <div class="flex-1 overflow-auto">
          <div class="p-2">
            <div v-for="item in filteredFileTree" :key="item.path">
              <FileTreeItem 
                :item="item" 
                :current-file="currentFile"
                @select="selectFile"
                @rename="renameFile"
                @delete="deleteItem"
                @toggle="toggleFolder"
              />
            </div>
          </div>
        </div>

        <!-- 文件操作按钮 -->
        <div class="p-3 border-t border-gray-200 dark:border-gray-700">
          <button 
            @click="createNewFile"
            class="w-full flex items-center justify-center px-3 py-2 text-sm bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
          >
            <FilePlus class="w-4 h-4 mr-2" />
            新建文件
          </button>
        </div>
      </div>

      <!-- 编辑器区域 -->
      <div class="editor-container flex-1 flex flex-col">
        <!-- 编辑器工具栏 -->
        <div class="editor-toolbar flex items-center justify-between px-4 py-2 bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-700">
          <!-- 格式化工具 -->
          <div class="flex items-center space-x-1">
            <button 
              @click="insertBold"
              class="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-md transition-colors"
              title="加粗"
            >
              <Bold class="w-4 h-4" />
            </button>
            <button 
              @click="insertItalic"
              class="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-md transition-colors"
              title="斜体"
            >
              <Italic class="w-4 h-4" />
            </button>
            <button 
              @click="insertStrikethrough"
              class="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-md transition-colors"
              title="删除线"
            >
              <Strikethrough class="w-4 h-4" />
            </button>
            <div class="w-px h-6 bg-gray-300 dark:bg-gray-600"></div>
            <button 
              @click="insertHeading"
              class="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-md transition-colors"
              title="标题"
            >
              <Heading class="w-4 h-4" />
            </button>
            <button 
              @click="insertLink"
              class="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-md transition-colors"
              title="链接"
            >
              <Link class="w-4 h-4" />
            </button>
            <button 
              @click="insertImage"
              class="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-md transition-colors"
              title="图片"
            >
              <Image class="w-4 h-4" />
            </button>
            <button 
              @click="insertCode"
              class="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-md transition-colors"
              title="代码"
            >
              <Code class="w-4 h-4" />
            </button>
            <button 
              @click="insertTable"
              class="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-md transition-colors"
              title="表格"
            >
              <Table class="w-4 h-4" />
            </button>
          </div>

          <!-- 视图模式切换 -->
          <div class="flex items-center bg-gray-100 dark:bg-gray-800 rounded-lg p-1 shadow-inner">
            <button 
              @click="viewMode = 'edit'"
              class="flex items-center px-4 py-2 text-sm font-medium rounded-md transition-all duration-200"
              :class="viewMode === 'edit' 
                ? 'bg-white dark:bg-gray-700 text-blue-600 dark:text-blue-400 shadow-sm transform scale-105' 
                : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700'"
            >
              <Edit class="w-4 h-4 mr-2" />
              编辑
            </button>
            <button 
              @click="viewMode = 'split'"
              class="flex items-center px-4 py-2 text-sm font-medium rounded-md transition-all duration-200"
              :class="viewMode === 'split' 
                ? 'bg-white dark:bg-gray-700 text-blue-600 dark:text-blue-400 shadow-sm transform scale-105' 
                : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700'"
            >
              <Columns class="w-4 h-4 mr-2" />
              分屏
            </button>
            <button 
              @click="viewMode = 'preview'"
              class="flex items-center px-4 py-2 text-sm font-medium rounded-md transition-all duration-200"
              :class="viewMode === 'preview' 
                ? 'bg-white dark:bg-gray-700 text-blue-600 dark:text-blue-400 shadow-sm transform scale-105' 
                : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700'"
            >
              <Eye class="w-4 h-4 mr-2" />
              预览
            </button>
          </div>
        </div>

        <!-- 编辑器内容区 -->
        <div class="editor-content flex-1 flex overflow-hidden">
          <!-- 编辑区域 -->
          <div 
            v-if="viewMode === 'edit' || viewMode === 'split'"
            :class="viewMode === 'split' ? 'w-1/2' : 'w-full'"
            class="edit-pane border-r border-gray-200 dark:border-gray-700 relative"
          >
            <textarea
              ref="editorTextarea"
              v-model="content"
              class="w-full h-full p-4 resize-none border-none outline-none bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100 font-mono text-sm leading-relaxed"
              placeholder="开始编写您的 Markdown 文档..."
              @input="handleContentChange"
              @scroll="syncScroll"
              @keydown="handleKeydown"
              style="padding-left: 3rem;"
            />
            
            <!-- 行号 -->
            <div class="absolute left-0 top-0 w-12 h-full bg-gray-50 dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700 overflow-hidden">
              <div class="p-4 text-xs text-gray-400 font-mono leading-relaxed">
                <div v-for="(line, index) in contentLines" :key="index" class="h-6">
                  {{ index + 1 }}
                </div>
              </div>
            </div>
          </div>

          <!-- 预览区域 -->
          <div 
            v-if="viewMode === 'preview' || viewMode === 'split'"
            :class="viewMode === 'split' ? 'w-1/2' : 'w-full'"
            class="preview-pane bg-white dark:bg-gray-900 overflow-auto"
            ref="previewPane"
          >
            <div class="p-6">
              <MarkdownRenderer :content="content" />
            </div>
          </div>
        </div>
      </div>

      <!-- AI助手面板 -->
      <div 
        v-if="aiOpen"
        class="ai-panel w-80 bg-gray-50 dark:bg-gray-800 border-l border-gray-200 dark:border-gray-700 flex flex-col"
      >
        <div class="p-4 border-b border-gray-200 dark:border-gray-700">
          <div class="flex items-center justify-between">
            <h3 class="text-sm font-semibold text-gray-700 dark:text-gray-300">AI 助手</h3>
            <button @click="toggleAI" class="p-1 hover:bg-gray-200 dark:hover:bg-gray-700 rounded">
              <X class="w-4 h-4" />
            </button>
          </div>
        </div>
        <div class="flex-1 p-4">
          <p class="text-sm text-gray-600 dark:text-gray-400">AI 助手功能开发中...</p>
        </div>
      </div>

      <!-- Git面板 -->
      <div 
        v-if="gitOpen"
        class="git-panel w-80 bg-gray-50 dark:bg-gray-800 border-l border-gray-200 dark:border-gray-700 flex flex-col"
      >
        <div class="p-4 border-b border-gray-200 dark:border-gray-700">
          <div class="flex items-center justify-between">
            <h3 class="text-sm font-semibold text-gray-700 dark:text-gray-300">Git 版本控制</h3>
            <button @click="toggleGit" class="p-1 hover:bg-gray-200 dark:hover:bg-gray-700 rounded">
              <X class="w-4 h-4" />
            </button>
          </div>
        </div>
        <div class="flex-1 p-4">
          <p class="text-sm text-gray-600 dark:text-gray-400">Git 功能开发中...</p>
        </div>
      </div>

      <!-- 设置面板 -->
      <div 
        v-if="settingsOpen"
        class="settings-panel w-80 bg-gray-50 dark:bg-gray-800 border-l border-gray-200 dark:border-gray-700 flex flex-col"
      >
        <div class="p-4 border-b border-gray-200 dark:border-gray-700">
          <div class="flex items-center justify-between">
            <h3 class="text-sm font-semibold text-gray-700 dark:text-gray-300">设置</h3>
            <button @click="toggleSettings" class="p-1 hover:bg-gray-200 dark:hover:bg-gray-700 rounded">
              <X class="w-4 h-4" />
            </button>
          </div>
        </div>
        <div class="flex-1 p-4">
          <p class="text-sm text-gray-600 dark:text-gray-400">设置功能开发中...</p>
        </div>
      </div>
    </div>

    <!-- 底部状态栏 -->
    <div class="statusbar flex items-center justify-between px-4 py-2 bg-gray-50 dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 text-xs text-gray-600 dark:text-gray-400">
      <!-- 左侧状态 -->
      <div class="flex items-center space-x-4">
        <span class="flex items-center">
          <FileText class="w-3 h-3 mr-1" />
          {{ currentFile }}
        </span>
        <span class="flex items-center">
          <Type class="w-3 h-3 mr-1" />
          {{ wordCount }} 词
        </span>
        <span class="flex items-center">
          <Hash class="w-3 h-3 mr-1" />
          {{ characterCount }} 字符
        </span>
        <span class="flex items-center">
          <MapPin class="w-3 h-3 mr-1" />
          第 {{ cursorLine }} 行，第 {{ cursorColumn }} 列
        </span>
      </div>

      <!-- 右侧状态 -->
      <div class="flex items-center space-x-4">
        <span class="flex items-center">
          <Code class="w-3 h-3 mr-1" />
          Markdown
        </span>
        <span class="flex items-center" :class="{ 'text-green-600': !isModified, 'text-orange-600': isModified }">
          <CheckCircle v-if="!isModified" class="w-3 h-3 mr-1" />
          <Circle v-else class="w-3 h-3 mr-1" />
          {{ isModified ? '未保存' : '已保存' }}
        </span>
        <span class="flex items-center">
          <GitCommit class="w-3 h-3 mr-1" />
          main
        </span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue';
import { 
  Menu, Plus, FolderOpen, Save, Brain, GitBranch, Settings, 
  Sun, Moon, Folder, RefreshCw, Search, FileText, 
  Trash2, Bold, Italic, Strikethrough, Heading, Link, 
  Image, Code, Table, Eye, Columns, Edit, MapPin, 
  CheckCircle, Circle, GitCommit, ChevronRight, ChevronDown,
  FolderPlus, FilePlus, Type, Hash, X
} from 'lucide-vue-next';
import FileTreeItem from '@/components/FileTreeItem.vue';
import MarkdownRenderer from '@/components/MarkdownRenderer.vue';
import { fileService, type FileItem } from '@/services/fileService';

// 响应式状态
const sidebarOpen = ref(true);
const aiOpen = ref(false);
const gitOpen = ref(false);
const settingsOpen = ref(false);
const isDark = ref(false);

// 文件管理
const currentFile = ref('欢迎.md');
const content = ref(`# 欢迎使用 Markdown 编辑器

这是一个功能强大的跨平台 Markdown 编辑器，具有以下特性：

## ✨ 主要功能

- **实时预览** - 支持编辑、分屏、预览三种模式
- **智能 AI 助手** - 提供写作建议和内容优化
- **Git 集成** - 完整的版本控制功能
- **文件管理** - 高效的文件组织和搜索
- **主题切换** - 支持深色和浅色主题

## 🚀 快速开始

1. 点击左上角的 **+** 按钮创建新文件
2. 使用工具栏的格式化按钮美化文档
3. 点击右上角的 🤖 图标体验 AI 助手
4. 使用 **Ctrl/Cmd + S** 保存文档

## 📝 Markdown 语法示例

### 文本格式
- **粗体文本**
- *斜体文本*
- ~~删除线~~
- \`行内代码\`

### 代码块
\`\`\`javascript
function hello() {
    console.log("Hello, Markdown!");
}
\`\`\`

### 表格
| 功能 | 状态 | 描述 |
|------|------|------|
| 编辑器 | ✅ | 完整的 Markdown 编辑功能 |
| 预览 | ✅ | 实时渲染预览 |
| AI 助手 | ✅ | 智能写作辅助 |

开始您的创作之旅吧！🎉`);

const isModified = ref(false);
const viewMode = ref('split');
const searchQuery = ref('');

// 文件树结构
const fileTree = ref([
  {
    name: '项目文档',
    path: '/docs',
    type: 'folder',
    expanded: true,
    children: [
      { name: '欢迎.md', path: '/docs/welcome.md', type: 'file', content: content.value },
      { name: 'README.md', path: '/docs/README.md', type: 'file', content: '# 项目说明\n\n这是一个示例项目。' }
    ]
  },
  {
    name: '个人笔记',
    path: '/notes',
    type: 'folder',
    expanded: false,
    children: [
      { name: '笔记.md', path: '/notes/notes.md', type: 'file', content: '# 我的笔记\n\n记录一些重要的想法...' },
      { name: '待办事项.md', path: '/notes/todo.md', type: 'file', content: '# 待办事项\n\n- [ ] 完成项目文档\n- [ ] 优化用户界面' }
    ]
  },
  { name: '快速开始.md', path: '/quick-start.md', type: 'file', content: '# 快速开始\n\n欢迎使用Markdown编辑器！' }
]);

// 编辑器引用
const editorTextarea = ref<HTMLTextAreaElement>();
const previewPane = ref<HTMLElement>();

// 计算属性
const filteredFileTree = computed(() => {
  if (!searchQuery.value) return fileTree.value;
  
  const filterTree = (items: any[]): any[] => {
    return items.reduce((acc, item) => {
      if (item.type === 'file' && item.name.toLowerCase().includes(searchQuery.value.toLowerCase())) {
        acc.push(item);
      } else if (item.type === 'folder' && item.children) {
        const filteredChildren = filterTree(item.children);
        if (filteredChildren.length > 0) {
          acc.push({
            ...item,
            children: filteredChildren,
            expanded: true
          });
        }
      }
      return acc;
    }, []);
  };
  
  return filterTree(fileTree.value);
});

const contentLines = computed(() => content.value.split('\n'));
const wordCount = computed(() => content.value.split(/\s+/).filter(word => word.length > 0).length);
const characterCount = computed(() => content.value.length);
const cursorLine = ref(1);
const cursorColumn = ref(1);

// 方法
const toggleSidebar = () => { sidebarOpen.value = !sidebarOpen.value; };
const toggleAI = () => { aiOpen.value = !aiOpen.value; };
const toggleGit = () => { gitOpen.value = !gitOpen.value; };
const toggleSettings = () => { settingsOpen.value = !settingsOpen.value; };

const toggleTheme = () => {
  isDark.value = !isDark.value;
  document.documentElement.classList.toggle('dark', isDark.value);
};

// 递归查找文件
const findFileInTree = (tree: any[], fileName: string): any => {
  for (const item of tree) {
    if (item.type === 'file' && item.name === fileName) {
      return item;
    }
    if (item.type === 'folder' && item.children) {
      const found = findFileInTree(item.children, fileName);
      if (found) return found;
    }
  }
  return null;
};

// 递归添加文件到树
const addFileToTree = (tree: any[], file: any, parentPath = '') => {
  tree.push(file);
};

const newFile = async () => {
  try {
    const fileName = `新文档${Date.now()}.md`;
    const initialContent = '# 新文档\n\n开始编写...';
    
    const filePath = await fileService.saveFile(fileName, initialContent);
    
    const newFileObj = {
      name: fileName,
      path: filePath,
      type: 'file',
      content: initialContent
    };
    
    addFileToTree(fileTree.value, newFileObj);
    selectFile(newFileObj);
  } catch (error) {
    console.error('创建新文件失败:', error);
    alert('创建新文件失败，请重试');
  }
};

const openFile = async () => {
  try {
    const fileData = await fileService.openFile();
    if (fileData) {
      const fileObj = {
        name: fileData.name,
        path: fileData.path,
        type: 'file',
        content: fileData.content
      };
      
      const existingFile = findFileInTree(fileTree.value, fileData.name);
      if (!existingFile) {
        addFileToTree(fileTree.value, fileObj);
      }
      
      selectFile(fileObj);
    }
  } catch (error) {
    console.error('打开文件失败:', error);
    alert('打开文件失败，请重试');
  }
};

const saveFile = async () => {
  try {
    if (!currentFile.value) return;
    
    const currentFileObj = findFileInTree(fileTree.value, currentFile.value);
    if (currentFileObj) {
      await fileService.saveFile(currentFileObj.path, content.value);
      currentFileObj.content = content.value;
      isModified.value = false;
      console.log('文件已保存:', currentFile.value);
    } else {
      await saveAsFile();
    }
  } catch (error) {
    console.error('保存文件失败:', error);
    alert('保存文件失败，请重试');
  }
};

const saveAsFile = async () => {
  try {
    const filePath = await fileService.saveAsFile(content.value);
    if (filePath) {
      const fileName = filePath.split('/').pop() || '未命名.md';
      const fileObj = {
        name: fileName,
        path: filePath,
        type: 'file',
        content: content.value
      };
      
      addFileToTree(fileTree.value, fileObj);
      currentFile.value = fileName;
      isModified.value = false;
    }
  } catch (error) {
    console.error('另存为失败:', error);
    alert('另存为失败，请重试');
  }
};

const selectFile = (file: any) => {
  currentFile.value = file.name;
  content.value = file.content;
  isModified.value = false;
};

const toggleFolder = (folder: any) => {
  folder.expanded = !folder.expanded;
};

const renameFile = (item: any) => {
  const newName = prompt('请输入新名称:', item.name);
  if (newName && newName !== item.name) {
    item.name = newName;
    if (currentFile.value === item.name) {
      currentFile.value = newName;
    }
  }
};

const deleteItem = (item: any) => {
  if (confirm(`确定要删除 "${item.name}" 吗？`)) {
    const removeFromTree = (tree: any[], targetItem: any) => {
      for (let i = 0; i < tree.length; i++) {
        if (tree[i] === targetItem) {
          tree.splice(i, 1);
          return true;
        }
        if (tree[i].children && removeFromTree(tree[i].children, targetItem)) {
          return true;
        }
      }
      return false;
    };
    
    removeFromTree(fileTree.value, item);
    
    if (currentFile.value === item.name) {
      const firstFile = findFirstFile(fileTree.value);
      if (firstFile) {
        selectFile(firstFile);
      } else {
        currentFile.value = '未命名.md';
        content.value = '';
      }
    }
  }
};

const findFirstFile = (tree: any[]): any => {
  for (const item of tree) {
    if (item.type === 'file') {
      return item;
    }
    if (item.type === 'folder' && item.children) {
      const found = findFirstFile(item.children);
      if (found) return found;
    }
  }
  return null;
};

const createNewFile = () => newFile();

const createNewFolder = async () => {
  const folderName = prompt('请输入文件夹名称:', '新文件夹');
  if (folderName) {
    try {
      const folderPath = await fileService.createFolder(folderName);
      const newFolder = {
        name: folderName,
        path: folderPath,
        type: 'folder',
        expanded: true,
        children: []
      };
      fileTree.value.push(newFolder);
    } catch (error) {
      console.error('创建文件夹失败:', error);
      alert('创建文件夹失败，请重试');
    }
  }
};

const refreshFiles = async () => {
  try {
    const files = await fileService.listFiles();
    fileTree.value = convertToFileTree(files);
  } catch (error) {
    console.error('刷新文件列表失败:', error);
    alert('刷新文件列表失败，请重试');
  }
};

const convertToFileTree = (files: FileItem[]): any[] => {
  const tree: any[] = [];
  const folderMap = new Map();
  
  files.forEach(file => {
    if (file.type === 'folder') {
      const folderItem = {
        name: file.name,
        path: file.path,
        type: 'folder',
        expanded: false,
        children: []
      };
      folderMap.set(file.path, folderItem);
      tree.push(folderItem);
    }
  });
  
  files.forEach(file => {
    if (file.type === 'file') {
      const fileItem = {
        name: file.name,
        path: file.path,
        type: 'file',
        content: file.content || ''
      };
      
      const parentPath = file.path.substring(0, file.path.lastIndexOf('/'));
      const parentFolder = folderMap.get(parentPath);
      
      if (parentFolder) {
        parentFolder.children.push(fileItem);
      } else {
        tree.push(fileItem);
      }
    }
  });
  
  return tree;
};

const handleContentChange = () => {
  isModified.value = true;
  updateCursorPosition();
};

const updateCursorPosition = () => {
  if (editorTextarea.value) {
    const textarea = editorTextarea.value;
    const text = textarea.value.substring(0, textarea.selectionStart);
    const lines = text.split('\n');
    cursorLine.value = lines.length;
    cursorColumn.value = lines[lines.length - 1].length + 1;
  }
};

// 格式化工具
const insertBold = () => insertFormat('**', '**');
const insertItalic = () => insertFormat('*', '*');
const insertStrikethrough = () => insertFormat('~~', '~~');
const insertCode = () => insertFormat('`', '`');
const insertHeading = () => insertFormat('# ', '');
const insertLink = () => insertFormat('[', '](https://example.com)');
const insertImage = () => insertFormat('![', '](https://via.placeholder.com/400x200)');
const insertTable = () => {
  const table = `
| 列1 | 列2 | 列3 |
|-----|-----|-----|
| 内容1 | 内容2 | 内容3 |
| 内容4 | 内容5 | 内容6 |
`;
  insertText(table);
};

const insertFormat = (before: string, after: string) => {
  if (editorTextarea.value) {
    const textarea = editorTextarea.value;
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const selectedText = content.value.substring(start, end);
    const newText = before + selectedText + after;
    
    content.value = content.value.substring(0, start) + newText + content.value.substring(end);
    isModified.value = true;
    
    nextTick(() => {
      textarea.focus();
      textarea.setSelectionRange(start + before.length, start + before.length + selectedText.length);
    });
  }
};

const insertText = (text: string) => {
  if (editorTextarea.value) {
    const textarea = editorTextarea.value;
    const start = textarea.selectionStart;
    
    content.value = content.value.substring(0, start) + text + content.value.substring(start);
    isModified.value = true;
    
    nextTick(() => {
      textarea.focus();
      textarea.setSelectionRange(start + text.length, start + text.length);
    });
  }
};

const handleKeydown = (event: KeyboardEvent) => {
  if (event.ctrlKey || event.metaKey) {
    switch (event.key) {
      case 's':
        event.preventDefault();
        saveFile();
        break;
      case 'n':
        event.preventDefault();
        newFile();
        break;
      case 'b':
        event.preventDefault();
        insertBold();
        break;
      case 'i':
        event.preventDefault();
        insertItalic();
        break;
    }
  }
};

const syncScroll = () => {
  if (viewMode.value === 'split' && editorTextarea.value && previewPane.value) {
    const scrollRatio = editorTextarea.value.scrollTop / (editorTextarea.value.scrollHeight - editorTextarea.value.clientHeight);
    previewPane.value.scrollTop = scrollRatio * (previewPane.value.scrollHeight - previewPane.value.clientHeight);
  }
};

// 初始化
onMounted(() => {
  if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
    isDark.value = true;
    document.documentElement.classList.add('dark');
  }
  
  window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
    if (e.matches) {
      isDark.value = true;
      document.documentElement.classList.add('dark');
    } else {
      isDark.value = false;
      document.documentElement.classList.remove('dark');
    }
  });
});
</script>

<style scoped>
/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: transparent;
}

::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 0, 0, 0.3);
}

.dark ::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.2);
}

.dark ::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.3);
}

/* 动画效果 */
.file-item,
.editor-toolbar button,
.titlebar button {
  transition: all 0.2s ease;
}

/* macOS 风格毛玻璃效果 */
.titlebar,
.statusbar {
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    position: absolute;
    left: 0;
    top: 0;
    height: 100%;
    z-index: 10;
    box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
  }
  
  .ai-panel,
  .git-panel,
  .settings-panel {
    position: absolute;
    right: 0;
    top: 0;
    height: 100%;
    z-index: 10;
    box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
  }
}
</style>
